import { Badge, Button, Checkbox, Col, Divider, Radio, Row, Space, Spin, Tag } from 'antd';
import React, { useEffect, useState } from 'react';
import { CheckboxChangeEvent } from 'antd/es/checkbox';
import * as utils from '@/utils/utils';
import * as apiChecker from '@/services/checkServer';
import { CheckboxValueType } from 'antd/es/checkbox/Group';

export type CheckServerProps = {
  width: number | undefined;
  initValues?: any[] | undefined;
  onChange: (serverIds: CheckboxValueType[], valueType?: string) => void;
  displayType?: string;
  showDisplayType?: boolean;
};

const FlagImage: React.FC<CheckServerProps> = (props) => {
  const {onChange, width, initValues, displayType, showDisplayType} = props;

  
  const [myloading, setMyloading] = useState<boolean>(true);
  const [dataCheckers, setDataCheckers] = useState<API.CheckServer[] | undefined>(undefined);
  const [dataGroupNames, setDataGroupNames] = useState<string[] | undefined>(undefined);
  const [dataDisplayType, setDataDisplayType] = useState<string | undefined>(displayType);
  const [checkedList, setCheckedList] = useState<any[]>(initValues ?? []);


  const checkAll = dataDisplayType == 'group' ? dataGroupNames?.length === checkedList?.length : dataCheckers?.length === checkedList?.length;
  const indeterminate = dataDisplayType == 'group' ? checkedList?.length > 0 && checkedList?.length < dataGroupNames?.length : checkedList?.length > 0 && checkedList?.length < dataCheckers?.length;
  const onCheckAllChange = (e: CheckboxChangeEvent) => {
    if(dataDisplayType == 'group'){
      setCheckedList(e.target.checked ? dataGroupNames?.map((val)=>val) : []);
    }
    else{
      setCheckedList(e.target.checked ? dataCheckers?.map((val)=>val.id) : []);
    }
  };

  
  const loadData = async () => {
    const resultChecker = await apiChecker.list();
    if (resultChecker && resultChecker.data) {
      setDataCheckers(resultChecker.data);
      let groupNames = [];
      for(let item of resultChecker.data){
        if(!item.groupName) continue;
        if(groupNames.includes(item.groupName)) continue;
        groupNames.push(item.groupName);
      }
      setDataGroupNames(groupNames);
    } else {
      setDataCheckers([]);
      setDataGroupNames([]);
    }

    setMyloading(false);
  };

  useEffect(() => {
    loadData();
  }, []);

  const handleSelectServers = () => {
    let sels = [];
    let groupNames = [];
    // console.log(dataDisplayType, dataGroupNames);
    if(dataDisplayType == 'group'){
      if(dataGroupNames){
        for(let item of dataGroupNames){
          if(groupNames.includes(item)) continue;
          groupNames.push(item);
          sels.push(item);
        }
      }
    }
    else{
      if(dataCheckers){
        for(let item of dataCheckers){
          if(!item.groupName) continue;
          if(item.status != true) continue;
          if(item.taskCount > 0) continue;
          if(groupNames.includes(item.groupName)) continue;
          if(item.groupName.toLowerCase().indexOf('-auto') != -1 || item.groupName.toLowerCase().indexOf('auto-') != -1) continue;
          groupNames.push(item.groupName);
          sels.push(item.id);
        }
      }
    }

    // console.log(sels);
    setCheckedList(sels);
    handleCheckChange(sels);
  };

  const handleCheckChange = (values:any[]) => {
    onChange(values, dataDisplayType == 'group' ? 'group' : 'server');
  }

  return (
    <Space>
    <Spin spinning={myloading}>
      <Row gutter={24} style={{width:width ? width : '100%', marginBottom:10}}>
        <Col span={24}>
          <Checkbox indeterminate={indeterminate} onChange={onCheckAllChange} checked={checkAll}>全选</Checkbox>
          <Button type="link" onClick={handleSelectServers}>一键选取</Button>
          {showDisplayType == true ?
          <span>
            <Radio.Group
              defaultValue={dataDisplayType == 'group' ? 'g' : 's'}
              buttonStyle="solid"
            >
              <Radio.Button
                value="s"
                onClick={() => {
                  setDataDisplayType('server');
                  setCheckedList([]);
                  handleCheckChange([]);
                }}
              >
                服务器
              </Radio.Button>
              <Radio.Button
                value="g"
                onClick={() => {
                  setDataDisplayType('group');
                  setCheckedList([]);
                  handleCheckChange([]);
                }}
              >
                分组
              </Radio.Button>
            </Radio.Group>
          </span> : ''}
        </Col>
      </Row>
      
      <Checkbox.Group key="ckgPlat" onChange={(checkedValue) =>{ 
        // console.log(checkedValue);
        setCheckedList(checkedValue);
        handleCheckChange(checkedValue);
      }} value={checkedList}>
        <Row gutter={24} style={{width:width ? width : '100%'}}>
          {dataDisplayType == "group" ? 
          dataGroupNames?.map((gc) => {
            return (
              <Col span={4}><Space><Checkbox value={gc} style={{ verticalAlign: 'middle' }}><Space>
                <Tag color={utils.getTextRanColor(gc)}>{gc}</Tag>
                </Space>
              </Checkbox></Space></Col>
            );
          })
          : utils.listHtoV(dataCheckers, 3)?.map((gc) => {
            let text = <Tag color={gc.online == true ? 'green' : 'error'}>{gc.groupName ? <Tag color={utils.getTextRanColor(gc.groupName)}>{gc.groupName}</Tag> : ''}
              {gc.name} [{gc.id}]</Tag>;
            return (
              <Col span={8}><Space><Checkbox value={gc.id} style={{ verticalAlign: 'middle' }}><Space>
                {gc.status ? (
                  <Badge color="#52c41a" />
                ) : (
                  <Badge color="#f50" />
                )}
                {text}
                <Badge count={gc.taskCount} style={{marginLeft:-13, backgroundColor:'#faad14'}}/></Space>
              </Checkbox></Space></Col>
            );
          })}

        </Row>
      </Checkbox.Group>
    </Spin>
    </Space>
  );
};

export default FlagImage;
